//
//  CXLFMDBManager.swift
//  FMDB演练
//
//  Created by 曹晓龙 on 15/10/30.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit

/// 数据库文件名
private let sqName = "sq.db"

/// FMDB 管理工具类
class CXLFMDBManager {
    
    //MARK: -单例
    static let sharedFMDBManger:CXLFMDBManager = CXLFMDBManager()
    
    /// 队列
    let queue:FMDatabaseQueue
    
    private init(){
        
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        path = (path as NSString).stringByAppendingPathComponent(sqName)

        QL2Info("数据库沙盒地址\(path)")        
        queue = FMDatabaseQueue(path: path)

        createrTable()
    }
    
    ///  创建表格
    private func createrTable(){
        
        let path = NSBundle.mainBundle().pathForResource("sq.db", ofType: nil)!
        
        let sql = try! String(contentsOfFile: path)
        
        queue.inDatabase { (db) -> Void in
            db.executeStatements(sql)
        }
    }
    
    ///  查询数据库表格数据
    ///
    ///  - parameter sql: 执行代码
    ///
    ///  - returns: 数据库表格内容数组(没有内容,返回空数组  而不是nil)
    func selectedSQL(sql:String) -> [[String : AnyObject]]{
        
        var arrayM = [[String : AnyObject]]()
        
        CXLFMDBManager.sharedFMDBManger.queue.inDatabase { (db) -> Void in
            
            guard let set = db.executeQuery(sql) else{
                print("没有结果")
                
                return
            }
            
            while set.next(){
                
                let cols = set.columnCount()
                
                var dict = [String : AnyObject]()
                
                for col in 0..<cols{
                    
                    let name = set.columnNameForIndex(col)
                    
                    let obj = set.objectForColumnIndex(col)
                    
                    dict[name] = obj
                }
                
                arrayM.append(dict)
            }
        }
        return arrayM
    }
}